<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { ElDialog, ElScrollbar, ElTree, ElRow, ElCol, ElButton, TreeInstance } from 'element-plus'
import { getMenuListApi } from '@/api/menu'
import { Menu } from '@/api/menu/types'

const props = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: () => true
  },
  type: {
    type: String,
    default: () => ''
  }
})

const dialogVisibleValue = ref(false)

const treeRef = ref<TreeInstance>()

// 加载数据
const list = ref<Menu[]>([])
const loading = ref(false)
const loadList = async () => {
  loading.value = true
  const res = await getMenuListApi({})
  list.value = res.data
  defaultExpandedKeys.value = getExpandedKeys(res.data)
  await nextTick()
  console.log(props.value)
  if (props.value && props.value.length) {
    props.value?.forEach((_key: any) => {
      treeRef.value?.setChecked(_key, true, false)
    })
  }
  await nextTick()
  loading.value = false
}

const onDisabled = (value: boolean = false) => {
  dialogVisibleValue.value = value
}

const onSubmit = () => {
  let checkedNodes
  if (props.multiple) {
    const halfNodes = treeRef.value!.getHalfCheckedNodes() || []
    const nodes = treeRef.value!.getCheckedNodes() || []
    checkedNodes = halfNodes.concat(nodes)
  } else {
    checkedNodes = treeRef.value!.getCheckedNodes()
  }
  console.log(checkedNodes)
  emit('onConfirm', checkedNodes)
  dialogVisibleValue.value = false
}

const defaultProps = ref({
  children: 'child',
  label: 'name'
})

const defaultExpandedKeys = ref([])

const getExpandedKeys = (data) => {
  let keys = [] as any
  data.forEach((row) => {
    // console.log(row.type === 0)
    if (row.type === 0) {
      // 如果存在子级，并且子级也是菜单，就展开
      if (row.child && row.child.length && row.child[0].type === 0) {
        keys.push(row.id)
        const childrenKeys = getExpandedKeys(row.child)
        if (childrenKeys && childrenKeys.length) {
          keys = keys.concat(childrenKeys)
        }
      }
    }
  })
  return keys
}

const handleClick = (data, checked, node) => {
  console.log(data, checked, node)
  if (checked && !props.multiple) {
    // this.$refs.tree.setCheckedKeys([data.id])
    // 设置为单选
    // 每次选择的时候，只设置选中的这个节点
    treeRef.value!.setCheckedNodes([data])
  }
}

const emit = defineEmits(['onClose', 'onConfirm'])

const onOpen = () => {
  // 打开弹窗
  loadList()
}
const onOpened = () => {}
const onClose = () => {}
const onClosed = () => {
  emit('onClose', 'aaa', 'bbb')
  list.value = []
}

// 对外函数
defineExpose({
  onDisabled
})
</script>

<template>
  <el-dialog
    v-model="dialogVisibleValue"
    title="菜单信息"
    width="400px"
    :draggable="true"
    :close-on-click-modal="false"
    @open="onOpen"
    @opend="onOpened"
    @close="onClose"
    @closed="onClosed"
  >
    <el-row :gutter="20">
      <el-col :span="24">
        <el-scrollbar style="height: 400px; background-color: #fff">
          <el-tree
            ref="treeRef"
            :data="list"
            v-loading="loading"
            show-checkbox
            node-key="id"
            :default-expand-all="false"
            :check-strictly="!multiple"
            :props="defaultProps"
            :default-expanded-keys="defaultExpandedKeys"
            @check-change="handleClick"
          />
        </el-scrollbar>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-button type="primary" @click="onSubmit()">保存</el-button>
        <el-button @click="dialogVisibleValue = false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
